/**
 * 本地存储工具类
 */

const STORAGE_KEYS = {
	SPEED_CALC_RECORDS: 'speed_calc_records',
	RECENT_STATS: 'recent_stats',
	USER_SETTINGS: 'user_settings',
	SPEED_FORMULA_CHOICE_RECORDS: 'speed_formula_choice_records',
	SPEED_CALC_CHOICE_RECORDS: 'speed_calc_choice_records',
	SPEED_JUDGE_RECORDS: 'speed_judge_records',
	SPEED_JUDGE_CHOICE_RECORDS: 'speed_judge_choice_records'
};

class Storage {
	/**
	 * 设置存储数据
	 * @param {string} key 存储键
	 * @param {any} data 存储数据
	 */
	static set(key, data) {
		try {
			uni.setStorageSync(key, data);
			return true;
		} catch (e) {
			console.error('Storage set error:', e);
			return false;
		}
	}

	/**
	 * 获取存储数据
	 * @param {string} key 存储键
	 * @param {any} defaultValue 默认值
	 */
	static get(key, defaultValue = null) {
		try {
			const data = uni.getStorageSync(key);
			return data !== '' ? data : defaultValue;
		} catch (e) {
			console.error('Storage get error:', e);
			return defaultValue;
		}
	}

	/**
	 * 删除存储数据
	 * @param {string} key 存储键
	 */
	static remove(key) {
		try {
			uni.removeStorageSync(key);
			return true;
		} catch (e) {
			console.error('Storage remove error:', e);
			return false;
		}
	}

	/**
	 * 清空所有存储
	 */
	static clear() {
		try {
			uni.clearStorageSync();
			return true;
		} catch (e) {
			console.error('Storage clear error:', e);
			return false;
		}
	}

	/**
	 * 保存速算练习记录
	 * @param {Object} record 练习记录
	 */
	static saveSpeedCalcRecord(record) {
		const records = this.get(STORAGE_KEYS.SPEED_CALC_RECORDS, []);
		records.unshift({
			...record,
			id: Date.now().toString(),
			date: new Date().toISOString()
		});
		
		// 只保留最近100条记录
		if (records.length > 100) {
			records.splice(100);
		}
		
		this.set(STORAGE_KEYS.SPEED_CALC_RECORDS, records);
		this.updateRecentStats();
		return true;
	}

	/**
	 * 保存公式选择题练习记录
	 * @param {Object} record 练习记录
	 */
	static saveSpeedFormulaChoiceRecord(record) {
		const records = this.get(STORAGE_KEYS.SPEED_FORMULA_CHOICE_RECORDS, []);
		records.unshift({
			...record,
			id: Date.now().toString(),
			date: new Date().toISOString()
		});
		
		// 只保留最近50条记录
		if (records.length > 50) {
			records.splice(50);
		}
		
		this.set(STORAGE_KEYS.SPEED_FORMULA_CHOICE_RECORDS, records);
		this.updateRecentStats();
		return true;
	}

	/**
	 * 获取速算练习记录
	 * @param {number} limit 限制数量
	 */
	static getSpeedCalcRecords(limit = null) {
		const records = this.get(STORAGE_KEYS.SPEED_CALC_RECORDS, []);
		return limit ? records.slice(0, limit) : records;
	}

	/**
	 * 获取公式选择题练习记录
	 * @param {number} limit 限制数量
	 */
	static getSpeedFormulaChoiceRecords(limit = null) {
		const records = this.get(STORAGE_KEYS.SPEED_FORMULA_CHOICE_RECORDS, []);
		return limit ? records.slice(0, limit) : records;
	}

	/**
	 * 更新最近统计信息
	 */
	static updateRecentStats() {
		const calcRecords = this.getSpeedCalcRecords(5); // 最近5次速算练习
		const formulaRecords = this.getSpeedFormulaChoiceRecords(5); // 最近5次公式选择题练习
		
		// 合并所有记录并按时间排序
		const allRecords = [...calcRecords, ...formulaRecords]
		  .sort((a, b) => new Date(b.date) - new Date(a.date))
		  .slice(0, 10); // 取最近10次练习
		
		if (allRecords.length === 0) return;

		const stats = {
			practiceCount: allRecords.length,
			accuracy: Math.round(allRecords.reduce((sum, r) => sum + r.accuracy, 0) / allRecords.length),
			bestScore: Math.max(...allRecords.map(r => r.score || 0))
		};

		this.set(STORAGE_KEYS.RECENT_STATS, stats);
	}

	/**
	 * 获取用户设置
	 */
	static getUserSettings() {
		return this.get(STORAGE_KEYS.USER_SETTINGS, {
			defaultQuestionCount: 10,
			speedJudgeQuestionCount: 5,
			speedCalcQuestionCount: 10,
			preferredCalcTypes: ['add', 'subtract', 'multiply', 'divide'],
			preferredValueTypes: ['integer', 'decimal', 'percentage'],
			speedFormulaChoiceFormulas: ['formula1', 'formula2'],
			speedFormulaChoiceQuestionCount: 10,
			speedFormulaChoiceOptionsCount: 4,
			speedCalcChoiceQuestionCount: 10,
			speedJudgeChoiceQuestionCount: 10,
			speedJudgeChoiceOptionsCount: 4
		});
	}

	/**
	 * 保存用户设置
	 * @param {Object} settings 用户设置
	 */
	static saveUserSettings(settings) {
		const currentSettings = this.getUserSettings();
		const newSettings = { ...currentSettings, ...settings };
		return this.set(STORAGE_KEYS.USER_SETTINGS, newSettings);
	}
}

export default Storage;
export { STORAGE_KEYS };